# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :jwt_util.py
# @Time      :2022/5/29 0029 19:04
# @Author    :何胜利
from datetime import datetime, timedelta

import jwt
from flask import current_app


def generate_jwt(payload, expiry, secret=None):
    """
    生成jwt
    :param payload: dict 载荷
    :param expiry:  datatime 有效期
    :param secret:  盐
    :return:  返回token
    """

    # _payload = {
    #     "exp": expiry
    # }
    # _payload.update(payload)

    if "expiry" not in payload:
        payload["expiry"] = expiry

    # 判断盐是否存在
    if secret:
        secret = current_app.config["SECRET_KEY"]

    # 生成token  jwt.encode
    token = jwt.encode(payload, secret, algorithm="HS256")
    return token


def verify_jwt(token, secret=None):
    """
    校验token
    :param token:  token值
    :param secret:  盐
    :return:  payload 载荷
    """

    # 判断盐是否存在
    if not secret:
        secret = current_app.config["SECRET_KEY"]

        try:
            # 校验token jwt.decode
            payload = jwt.decode(token, secret, algorithms="HS256")
        except Exception as e:
            print("错误信息>>", e)
            # 校验失败返回None
            payload = None
        return payload


def _generate_token(user_id, refresh=True):
    """
    生成token
    :param user_id:
    :return:
    """
    # 获取盐
    secret = current_app.config['SECRET_KEY']
    # 定义过期时间
    expiry = datetime.utcnow() + timedelta(hours=60)
    # 生成token
    token = generate_jwt({"user_id": user_id}, str(expiry), secret)
    if refresh:
        expiry = datetime.utcnow() + timedelta(days=15)
        # is_refresh作为更新token的信号
        refresh_token = generate_jwt({"user_id": user_id, "is_refresh": True}, str(expiry), secret)
    else:
        refresh_token = None
    return token, refresh_token
